package com.xb.p28_messengerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;

public class MyService extends Service {
    final static String TAG="Messenger";
    final static int MSG_SEND_HELLO=1;
    final static int MSG_SET_HELLO=2;


    public MyService() {
    }

    class myHandler extends Handler{
        @Override
        public void handleMessage(@NonNull Message msg) {
            //接收客户端发来的消息
            switch (msg.what){
                case MSG_SEND_HELLO:
                    Toast.makeText(getApplicationContext(),"服务端接收到："+msg.getData().getString("data"),Toast.LENGTH_SHORT).show();
                    break;
            }

            //向activity发送小消息
            Message message=Message.obtain(null,MSG_SET_HELLO);
            Bundle bundle= new Bundle();
            bundle.putString("data2","服务发送消息：hello");
            message.setData(bundle);

            //使用来自客户端的信使，将消息发送回去
            try {
                msg.replyTo.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }

            super.handleMessage(msg);
        }
    }

    Messenger messenger =new Messenger(new myHandler());

    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG,"onBind");

        //通过IBinder将信使传递给客户端
        return messenger.getBinder();
    }
}